// product-detail.js
import api from './api.js';
import { checkLoginStatus, showMessage, formatPrice } from './common.js';

const { products, shoppingCart } = api;

// 加载商品详情
async function loadProductDetail() {
    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('id');
    if (!productId) return;

    try {
        const response = await products.get(productId);
        if (response.success) {
            renderProductDetail(response.data);
        } else {
            showMessage('error', '加载商品详情失败');
        }
    } catch (error) {
        showMessage('error', '加载商品详情失败');
    }
}

// 渲染商品详情
function renderProductDetail(product) {
    document.getElementById('product-name').textContent = product.name;
    document.getElementById('product-id').textContent = product.id;
    document.getElementById('price').textContent = formatPrice(product.price);
    document.getElementById('original-price').textContent = formatPrice(product.originalPrice);
    document.getElementById('stock').textContent = product.stock;
    document.getElementById('seller-name').textContent = product.seller?.username || '未知卖家';
    document.getElementById('seller-rating').textContent = product.seller?.rating || '★★★★★';

    // 加入购物车按钮事件
    document.getElementById('add-to-cart-btn')?.addEventListener('click', async function () {
        const user = await checkLoginStatus();
        if (!user) {
            showMessage('warning', '请先登录');
            window.location.href = 'login.html';
            return;
        }

        const quantity = parseInt(document.getElementById('quantity').value);
        try {
            const cartItem = {
                userId: user.id,
                productId: product.id,
                quantity,
                productName: product.name,
                productPrice: product.price,
                productImage: product.images?.[0] || 'default-product.jpg'
            };
            const response = await shoppingCart.add(cartItem);
            if (response.success) {
                showMessage('success', '已加入购物车');
            } else {
                showMessage('error', '加入购物车失败');
            }
        } catch (error) {
            showMessage('error', '加入购物车失败');
        }
    });
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', loadProductDetail);